import { login } from '@/api/user.js'

const userModule = {
  state: {
    userInfo: null,
    token: '',
  },
  mutations: { // 同步状态更新
    loginSuccess(state, payload) {
      state.userInfo = payload.userInfo
      state.token = payload.token
    },
    loginFaild(state) {
      state.userInfo = null
      state.token = ''
    },
  },
  actions: {
    loginAsync(state, payload) {
      return login(payload)
        .then(data => {
          console.log(data)
          const { userInfo: { username, nickname, avatarUrl, token } } = data
          // action 中不能直接更新状态，仍然需要提交 mutation
          state.commit('loginSuccess', {
            userInfo: { username, nickname, avatarUrl },
            token,
          })
          return true
        })
        .catch(err => {
          console.log('失败：', err)
          return false
        })
    },
  },
}

export default userModule
